<template>
    <div class="login-bg">
        <h1 class="blue-text">统一供应商管理平台</h1>
        <div class="form-login">
            <div class="login-logo"></div>
            <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                    size="default"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input
                            v-model="ruleForm.username"
                            autocomplete="off"
                    />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="验证码" prop="checkCode">
                    <el-row>
                        <el-col :span="12"><el-input style="height:38px" v-model="ruleForm.checkCode" placeholder="验证码" clearable @keyup.enter.native="submitForm"/></el-col>
                        <el-col :span="12"><img :src="imgSrc" style="width: 90%; margin-left:10px " @click="getCode" alt=""></el-col>
                    </el-row>
                </el-form-item>

<!--                <el-form-item label="验证码" prop="age">-->
<!--                    <el-input v-model.number="ruleForm.age" placeholder="验证码"/>-->
<!--                </el-form-item>-->
                <el-form-item>
                    <el-button style="width: 100%; background-image: linear-gradient(to right, rgb(123, 179, 253), rgb(23, 101, 251));" type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
<!--    <el-switch-->
<!--            v-model="value2"-->
<!--            class="mt-2"-->
<!--            style="margin-left: 24px"-->
<!--            inline-prompt-->
<!--            :active-icon="Sunny"-->
<!--            :inactive-icon="Moon"-->
<!--            @click="toggleDark()"-->
<!--    />-->
</template>

<script  setup lang="ts">
   import {ref,reactive,onMounted, onUpdated} from 'vue'
   import {useDark,useToggle} from '@vueuse/core'
   import {Sunny,Moon} from '@element-plus/icons-vue';
   import type { FormInstance } from 'element-plus'
   import {
       randCode,
       goLogin,
       firstLogin,
       findMenuList,
       queryAssessorCompany,
       getEnumeration,
       queryAreaList, searchProduct, queryCurrencyRate, Menu, searchFlagOfAES, saveQuote
   } from "@/api";
   import Crypto from "@/assets/Crypto";
   import http from "@/utils/axios";
   import {ElMessage} from "element-plus";
   import { useDataStore } from '@/store/data';
   import {storeToRefs} from "pinia";
   import {useRouter} from "vue-router";
   import {isNull, sm4encode} from "@/utils/sm4Util";
   import  CryptoJS from "@/home/core-sha256"
   import md5 from "@/home/md5"

   const isDark=useDark()
   const toggleDark=useToggle(isDark)
   const value2 = ref(false)
   const url='/czpt/api/system/login/randCode'
   const imgSrc=ref(`${window.location.protocol}//${window.location.host}${url}`)
   const ruleFormRef = ref<FormInstance>()
   const cry:any=new Crypto();
   const dataStore=useDataStore();
   const {username,sensorsOpen,menu,assessorCompany,areaLists,currencyRate}=storeToRefs(dataStore)
   const router=useRouter()
   // const md5:any=new URL('../../home/md5.js',import.meta.url).href
   const checkCode = (rule: any, value: any, callback: any) => {
       if (value==='') {
           return callback(new Error('Please input the code'))
       }else {
           callback()
       }
   }

   const validateUsername = (rule: any, value: any, callback: any) => {
       if (value === '') {
           callback(new Error('Please input the username'))
       } else {
           callback()
       }
   }
   const validatePassword = (rule: any, value: any, callback: any) => {
       if (value === '') {
           callback(new Error('Please input the password '))
       } else {
           callback()
       }
   }

   const ruleForm = reactive({
       username: '',
       password: '',
       checkCode: '',
   })

   const rules = reactive({
       username: [{ validator: validateUsername, trigger: 'blur' }],
       password: [{ validator: validatePassword, trigger: 'blur' }],
       checkCode: [{ validator: checkCode, trigger: 'blur' }],
   })

   const submitForm = async (formEl: FormInstance | undefined) => {
       if (isNull(rules.password) ||isNull(rules.username) ||isNull(rules.checkCode)) {
           ElMessage.error('用户名或者密码或者验证码没有填写')
           return;
       }
       //加密
       const entryData=CryptoJS(JSON.stringify(ruleForm.username+ruleForm.password))
       const j_word=sm4encode(JSON.stringify(entryData))
       const up_data={
           j_username:ruleForm.username,
           j_password:j_word,
           code:ruleForm.checkCode
       }
       // const up_data="j_password="+j_word+"&j_username="+ruleForm.username+"&code="+ruleForm.checkCode
       const config={
           headers:{
               "safe":(localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')||'{}'))?'safe':'unsafe',
               "MD5":(localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')||'{}'))?md5(up_data+'4%YKW!@g5LGcf9Ut'):''
           }
       }
       //解密
       // const decryptData=cry.decrypt(JSON.parse(entryData))

       // http({
       //     url:'/czpt/api/login?time='+new Date().getTime(),
       //     method:"POST",
       //     headers: config.headers,
       //     data:up_data
       // })
       if (!formEl) return
       await formEl.validate((valid) => {
           if (valid) {
               goLogin(up_data,{headers:config.headers}).then((data:string)=>{
                   let da:any=data
                   if((localStorage.getItem('safeFlag')&&JSON.parse(localStorage.getItem('safeFlag')||'{}'))&&typeof data==='string'){
                       da=data.replace(/[\r\n]/g,"")
                       da=decrypt(da)
                   }
                   if(!da){
                       ElMessage.error('登录失败')
                       return
                   }
                   da=JSON.parse(da)
                   if(decrypt(da.authorization)=="true"){
                       dataStore.$patch(state=>{
                           state.username={userCode:ruleForm.username,oldPassword:entryData}
                           window.sessionStorage.setItem('tokenId',da.tokenId)
                           firstLogin({code:ruleForm.username})
                               .then(function (res) {
                                   if(res.success){
                                           if(state.sensorsOpen)
                                           if(res.data.cafRole){
                                               window.sessionStorage.setItem('orgCode',res.data.cafRole.orgCode);
                                           }
                                       if(res.data.tGgrUserExt){
                                           window.sessionStorage.setItem('branchCode',res.data.tGrUserExt.branchCode);
                                           window.sessionStorage.setItem('ggrUserCode',res.data.tGrUserExt.branchCode);
                                           window.sessionStorage.setItem('ggrUserRole',res.data.userRoleList[0].roleId);
                                       }
                                       if(res.data.cafRole.orgCode=='1'){
                                           //认为是首次登录，强制更改密码
                                           state.username={userCode:ruleForm.username,oldPassword:ruleForm.password}
                                           router.push('/resetPassword');
                                       }else{
                                           //正常登录
                                           startLogin()
                                       }
                                   }else{
                                       //正常登录
                                       startLogin()
                                   }
                               })
                       })
                   }else{
                       ElMessage.error("登录失败")
                       getCode()
                   }
               }).catch(()=>{
                       ElMessage.error("登录失败!")
               })
           } else {
               // $message.warn('error submit!')
               ElMessage.error('error submit')
               return false
           }
       })
   }

   const startLogin=()=> {
       findMenuList({type: '11'}).then((res: any) => {
           dataStore.$patch(state => {
               state.menu = {
                   company: res.branchList,
                   productType: res.kindList,
                   productList: res.productList,
                   selectCompany: res.selectCompony
               }
           })
       })
       //公估公司枚举
       queryAssessorCompany({}).then(res => {
           if (res.data && res.data.companyList) {
               dataStore.$patch(state => {
                   state.assessorCompany = res.data.companyList
               })
           }
       })
       //公估人枚举
       getEnumeration({}).then((res: any) => {
           //币种处理
           if (res && res.data) {
               const rates = res.data.EM00000016
               res.data.EM00000016.map(function (item: any, index: number) {
                   if (item.code == 24) {
                       rates.splice(index, 1)
                   }
                   return rates;
               })
               const recoveryStatus = res.data.EM00000031.map(function (item: any) {
                   item.code = Number(item.code);
                   return item
               })
               dataStore.$patch(state => {
                   state.enumeration.EM00000001 = res.data.EM00000001
                   state.enumeration.EM00000002 = res.data.EM00000002
                   state.enumeration.EM00000003 = res.data.EM00000003
                   state.enumeration.EM00000004 = res.data.EM00000004
                   state.enumeration.EM00000005 = res.data.EM00000005
                   state.enumeration.EM00000006 = res.data.EM00000006
                   state.enumeration.EM00000007 = res.data.EM00000007
                   state.enumeration.EM00000008 = res.data.EM00000008
                   state.enumeration.EM00000009 = res.data.EM00000009
                   state.enumeration.EM00000010 = res.data.EM00000010
                   state.enumeration.EM00000011 = res.data.EM00000011
                   state.enumeration.EM00000012 = res.data.EM00000012
                   state.enumeration.EM00000013 = res.data.EM00000013
                   state.enumeration.EM00000014 = res.data.EM00000014
                   state.enumeration.EM00000015 = res.data.EM00000015
                   state.enumeration.EM00000016 = res.data.EM00000016
                   state.enumeration.EM00000017 = res.data.EM00000017
                   state.enumeration.EM00000018 = res.data.EM00000018
                   state.enumeration.EM00000019 = res.data.EM00000019
                   state.enumeration.EM00000020 = res.data.EM00000020
                   state.enumeration.EM00000021 = res.data.EM00000021
                   state.enumeration.EM00000022 = res.data.EM00000022
                   state.enumeration.EM00000023 = res.data.EM00000023
                   state.enumeration.EM00000024 = res.data.EM00000024
                   state.enumeration.EM00000025 = res.data.EM00000025
                   state.enumeration.EM00000025 = res.data.EM00000026
                   state.enumeration.EM00000025 = res.data.EM00000027
                   state.enumeration.EM00000025 = res.data.EM00000028
                   state.enumeration.EM00000025 = res.data.EM00000029
                   state.enumeration.EM00000025 = res.data.EM00000030
                   state.enumeration.EM00000031 = recoveryStatus
                   state.enumeration.EM00000033 = res.data.EM00000033
                   state.enumeration.EM00000034 = res.data.EM00000034
                   state.enumeration.EM00000035 = res.data.EM00000035
                   state.enumeration.EM00000036 = res.data.EM00000036
                   state.enumeration.EM00000037 = res.data.EM00000037
                   state.enumeration.EM00000038 = res.data.EM00000038
                   state.enumeration.EM00000039 = res.data.EM00000039
                   state.enumeration.EM00000040 = res.data.EM00000040
                   state.enumeration.EM00000041 = res.data.EM00000041
                   state.enumeration.EM00000042 = res.data.EM00000042
                   state.enumeration.EM00000043 = res.data.EM00000043
                   state.enumeration.EM00000044 = res.data.EM00000044
                   state.enumeration.EM00000045 = res.data.EM00000045
                   state.enumeration.EM00000046 = res.data.EM00000046
                   state.enumeration.EM00000047 = res.data.EM00000047
                   state.enumeration.EM00000048 = res.data.EM00000048
                   state.enumeration.EM00000049 = res.data.EM00000049
                   state.enumeration.EM00000050 = res.data.EM00000050
                   state.enumeration.EM00000051 = res.data.EM00000051
                   state.enumeration.EM00000052 = res.data.EM00000052
                   state.enumeration.EM00000053 = res.data.EM00000053
               })
           }
       });
       let areaLists: any[] = [];
       // 国家、省
       const areaParam = {
           level: 0,
           parentId: ''
       }
       //获取省市区
       queryAreaList({areaParam}).then(res => {
           if (res.success) {
               areaLists = res.data.map(function (value: any, i: number) {
                   return {
                       value: value.code,
                       label: value.name,
                       codeId: value.codeId,
                       children: []
                   }
               })
               var areaParam = {
                   level: 1,
                   parentId: '2184989'
               }
               queryAreaList({areaParam}).then(res=>{
                   if(res.success&& res.data){ //  加载市
                       areaLists.map(function(value, i) {
                           if (value.value=='156'&&!value.children.length) {
                               value.children = res.data.map(function(value:any, i:number) {
                                   return {
                                       value: value.code,
                                       label: value.name,
                                       codeId: value.codeId,
                                       children: []
                                   }
                               })
                           }
                       })
                       const area= {
                           areaLists: areaLists
                       }
                       dataStore.$patch(state=>{
                           state.areaLists=area
                       })
                   }
               })


           }
       });
       //公估人产品产险
       searchProduct({}).then(res=>{
           if(res.success){
               dataStore.$patch(state=>{
                   state.allProduct=res.data
               })
           }
       })
       //汇率
       queryCurrencyRate({}).then(res=>{
           if(res.success){
               dataStore.$patch(state=>{
                   state.currencyRate=res.data
               })
           }else{
               ElMessage.error(res.message)
           }
       })
       http({
           url:"/czpt/api/system/menu/"+dataStore.username,
           method:"POST",
       }).then(res=>{
           if(res.success){
               dataStore.$patch(state=>{
                   state.tabMenu=res.data
               })
           }
           switch (res.data[0].url) {
               case 'offer':router.push('/offer')
                   break;
               case 'recycleNew':router.push('/recycleNew')
                   break;
               case 'litigationProcessing':router.push('/litigationProcessing')
                   break;
               case 'exportProcessing':router.push('/exportProcessing')
                   break;
               case 'litResetPwd':router.push('/litResetPwd')
                   break;
               default:
                   router.push('/task')
                   break;
           }
       })
   }
   const resetForm = (formEl: FormInstance | undefined) => {
       if (!formEl) return
       formEl.resetFields()
   }
   getCode()
   async function getCode(){
       ruleForm.checkCode=''
       const Data='?random='+Math.random()
       imgSrc.value=`${window.location.protocol}//${window.location.host}${url}`+Data
   }
   const decrypt=(word:string)=>{
       let key=cry.encrypt.enc.Utf8('4%YKW!@g5LGcf9Ut')
       let decrypt=cry.encrypt.AES.decrypt(word,key,{mode:cry.encrypt.mode.ECB,padding:cry.encrypt.pad.Pkcs7})
       return cry.decrypt.enc.Utf8.stringify(decrypt).toString()
   }

   onMounted(()=>{
       searchFlagOfAES().then(function (res) {
           localStorage.setItem('safeFlag', res.data)
       }).catch(e=>{
           console.log(e)
       })
   })
   const safeFlag:any=false
   localStorage.setItem('safeFlag',safeFlag)

</script>

<style scoped>
    .login-bg{
        position: fixed;
        height: 100%;
        width: 100%;
        top: 0;
        bottom: 0;
        justify-content: center;
        align-items: center;
        background: url(../../assets/Wechat3.jpeg) no-repeat center center;
        background-size: cover;
    }
    .blue-text{
        font-size: 30px;
        color: #0d62ff;
        margin-top: 8% !important;
        text-align: center;
    }
    .form-login{
        max-width: 260px;
        padding: 0px 40px 30px;
        border-radius: 5px;
        margin: 0 auto;
    }
    .login-logo{
        left: 20px;
        display: flex;
        position: fixed;
        height: 37px;
        width: 150px;
        top: 20px;
        background: url(../../assets/Wechat2.png) no-repeat center center;
        background-size: 100% auto;
    }
</style>
